<template>
  <a-spin
    :loading="spinLoading"
    :size="35"
    class="w-[100%]"
    tip="正在处理, 请稍候..."
  >
    <a-space direction="vertical" fill size="medium">
      <!-- 基本信息 -->
      <a-descriptions :column="2" size="medium" bordered>
        <a-descriptions-item label="记录编号">
          {{ form.purchaseIndexRecordCode || "-" }}
        </a-descriptions-item>
        <a-descriptions-item label="购买时间">
          {{ form.purchaseTime || "-" }}
        </a-descriptions-item>
        <a-descriptions-item :span="2" label="备注">
          {{ form.remark || "暂无备注" }}
        </a-descriptions-item>
      </a-descriptions>

      <!-- 购买项目列表 -->
      <div v-if="form.purchaseItems && form.purchaseItems.length > 0">
        <a-divider orientation="left">购买项目列表</a-divider>
        <div v-for="(item, index) in form.purchaseItems" :key="index">
          <a-card class="mb-4">
            <a-descriptions :column="2" size="small" bordered>
              <a-descriptions-item label="镇街名称">
                {{ item.townName || "-" }}
              </a-descriptions-item>
              <a-descriptions-item label="购买亩数">
                {{ item.townIndex || "-" }}
              </a-descriptions-item>
            </a-descriptions>
            
            <!-- 合同文件 -->
            <div v-if="item.file" class="mt-4">
              <a-divider orientation="left" size="small">合同文件</a-divider>
              <a-list :data="[item.file]" :bordered="false">
                <template #item="{ item: file }">
                  <a-list-item>
                    <a-list-item-meta>
                      <template #avatar>
                        <icon-file-pdf
                          v-if="file.fileName && file.fileName.toLowerCase().includes('pdf')"
                          :size="24"
                        />
                        <icon-file v-else :size="24" />
                      </template>
                      <template #title>
                        {{ file.fileName }}
                      </template>
                    </a-list-item-meta>
                    <template #actions>
                      <a-button
                        type="text"
                        size="small"
                        @click="downloadFile(file)"
                      >
                        <template #icon><icon-download /></template>
                        下载
                      </a-button>
                      <a-button
                        type="text"
                        size="small"
                        @click="previewFile(file)"
                      >
                        <template #icon><icon-eye /></template>
                        预览
                      </a-button>
                    </template>
                  </a-list-item>
                </template>
              </a-list>
            </div>
            <div v-else class="mt-4 text-gray-500">
              <a-divider orientation="left" size="small">合同文件</a-divider>
              <div class="p-2 bg-gray-50 rounded text-sm">暂无合同文件</div>
            </div>
          </a-card>
        </div>
      </div>

      <!-- 相关附件 -->
      <div v-if="form.files && form.files.length > 0">
        <a-divider orientation="left">相关附件</a-divider>
        <a-card>
          <a-list :data="form.files" :bordered="false">
            <template #item="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #avatar>
                    <icon-file-pdf
                      v-if="item.fileName && item.fileName.toLowerCase().includes('pdf')"
                      :size="24"
                    />
                    <icon-file-image
                      v-else-if="item.fileName && (item.fileName.toLowerCase().includes('jpg') || item.fileName.toLowerCase().includes('png') || item.fileName.toLowerCase().includes('jpeg'))"
                      :size="24"
                    />
                    <icon-file v-else :size="24" />
                  </template>
                  <template #title>
                    {{ item.fileName || item.name }}
                  </template>
                  <template #description>
                    <div class="text-gray-500 text-sm">
                      <span v-if="item.createTime">上传时间: {{ item.createTime }}</span>
                      <span v-if="item.fileSize" class="ml-4">
                        文件大小: {{ formatFileSize(item.fileSize) }}
                      </span>
                    </div>
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-button
                    type="text"
                    size="small"
                    @click="downloadFile(item)"
                  >
                    <template #icon><icon-download /></template>
                    下载
                  </a-button>
                  <a-button
                    type="text"
                    size="small"
                    @click="previewFile(item)"
                  >
                    <template #icon><icon-eye /></template>
                    预览
                  </a-button>
                </template>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </div>

      <!-- 按钮区域 -->
      <div class="flex justify-center mt-6 pt-4 border-t border-gray-200">
        <a-button @click="onCancel">关闭</a-button>
      </div>
    </a-space>
  </a-spin>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, watch } from "vue";
import { getPurchaseIndexRecordByPurchaseIndexRecordIdApi } from "~/api/lindi/purchaseIndexRecord";
import {
  IconFile,
  IconFileImage,
  IconFilePdf,
  IconDownload,
  IconEye,
} from "@arco-design/web-vue/es/icon";
import { Message } from "@arco-design/web-vue";

// 定义props
const props = defineProps({
  params: {
    type: Object,
    default: () => ({}),
  },
});

// 定义emit
const emit = defineEmits(["ok", "cancel"]);

// 全局实例
const { proxy } = getCurrentInstance();

// 加载状态
const spinLoading = ref(false);

// 表单数据
const form = reactive({
  purchaseIndexRecordCode: "",
  purchaseIndexRecordId: null,
  purchaseItems: [], // 购买项目列表
  purchaseTime: "",
  files: [],
  remark: "", // 备注信息
});

// 监听参数变化
watch(
  () => props.params,
  () => {
    if (props.params.purchaseIndexRecordId) {
      loadRecordInfo(props.params.purchaseIndexRecordId);
    }
  },
  { deep: true, immediate: true }
);

// 加载记录信息
function loadRecordInfo(purchaseIndexRecordId) {
  spinLoading.value = true;

  getPurchaseIndexRecordByPurchaseIndexRecordIdApi(purchaseIndexRecordId)
    .then((res) => {
      console.log(res);
      if (res) {
        const data = { ...res };

        // 处理文件数据，确保文件列表正确显示
        if (data.files && Array.isArray(data.files)) {
          // 确保每个文件对象都有正确的属性
          data.files = data.files.map((file) => ({
            ...file,
            fileName: file.fileName || file.name,
            fileType:
              file.fileType ||
              (file.fileName ? file.fileName.split(".").pop() : ""),
            fileUrl: file.fileUrl || "",
            createTime: file.createTime || "",
          }));
        } else {
          data.files = [];
        }

        Object.assign(form, data);
      } else {
        proxy.$msg.error(res.msg || "获取购买指标记录详情失败");
      }
    })
    .catch((error) => {
      proxy.$msg.error("获取购买指标记录详情失败: " + error.message);
    })
    .finally(() => {
      spinLoading.value = false;
    });
}

// 下载文件
function downloadFile(file) {
  if (file && file.fileUrl) {
    window.open(file.fileUrl, "_blank");
  } else {
    Message.error("文件链接无效");
  }
}

// 预览文件
function previewFile(file) {
  if (file && file.fileUrl) {
    window.open(file.fileUrl, "_blank");
  } else {
    Message.error("文件链接无效");
  }
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (!bytes) return "";
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return Math.round((bytes / Math.pow(1024, i)) * 100) / 100 + " " + sizes[i];
}

// 取消
function onCancel() {
  emit("cancel");
}
</script>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}

.flex {
  display: flex;
}

.justify-center {
  justify-content: center;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.mb-2 {
  margin-bottom: 8px;
}

.mb-1 {
  margin-bottom: 4px;
}

.mt-4 {
  margin-top: 16px;
}

.mt-6 {
  margin-top: 24px;
}

.pt-4 {
  padding-top: 16px;
}

.p-2 {
  padding: 8px;
}

.ml-4 {
  margin-left: 16px;
}

.font-medium {
  font-weight: 500;
}

.text-gray-500 {
  color: #86909c;
}

.text-gray-600 {
  color: #4e5969;
}

.text-sm {
  font-size: 14px;
}

.bg-gray-50 {
  background-color: #f7f8fa;
}

.bg-blue-50 {
  background-color: #f0f9ff;
}

.rounded {
  border-radius: 4px;
}

.border-t {
  border-top-width: 1px;
}

.border-gray-200 {
  border-color: #e5e6eb;
}

.w-\[100\%\] {
  width: 100%;
}
</style>
